'use strict';

const { Sequelize } = require('sequelize');
const dbConfig = require('./config');

// 根据环境选择配置
const env = process.env.NODE_ENV || 'development';
const config = dbConfig[env];

// 创建 Sequelize 实例
const sequelize = new Sequelize(
  config.database,
  config.username,
  config.password,
  {
    host: config.host,
    port: config.port,
    dialect: config.dialect,
    timezone: config.timezone,
    define: config.define,
    pool: config.pool,
    logging: env === 'development' ? console.log : false, // 开发环境显示 SQL 日志
  }
);

// 配置模型关联关系
const setupAssociations = () => {
  // 延迟导入模型，避免循环依赖
  const User = require('../app/model/user');
  const TravelNote = require('../app/model/travelNote');
  const TravelNoteComment = require('../app/model/travelNoteComment');
  const { TravelNoteLike, TravelNoteFavorite } = require('../app/model/travelNoteInteraction');

  // User 和 TravelNote 的关联
  User.hasMany(TravelNote, {
    foreignKey: 'user_id',
    as: 'travelNotes'
  });
  TravelNote.belongsTo(User, {
    foreignKey: 'user_id',
    as: 'author'
  });

  // User 和 TravelNoteComment 的关联
  User.hasMany(TravelNoteComment, {
    foreignKey: 'user_id',
    as: 'comments'
  });
  TravelNoteComment.belongsTo(User, {
    foreignKey: 'user_id',
    as: 'user'
  });

  // TravelNote 和 TravelNoteComment 的关联
  TravelNote.hasMany(TravelNoteComment, {
    foreignKey: 'note_id',
    as: 'comments'
  });
  TravelNoteComment.belongsTo(TravelNote, {
    foreignKey: 'note_id',
    as: 'note'
  });

  // 评论的自关联（用于回复）
  TravelNoteComment.hasMany(TravelNoteComment, {
    foreignKey: 'parent_id',
    as: 'replies'
  });
  TravelNoteComment.belongsTo(TravelNoteComment, {
    foreignKey: 'parent_id',
    as: 'parent'
  });

  // User 和 TravelNoteLike 的关联
  User.hasMany(TravelNoteLike, {
    foreignKey: 'user_id',
    as: 'likes'
  });
  TravelNoteLike.belongsTo(User, {
    foreignKey: 'user_id',
    as: 'user'
  });

  // TravelNote 和 TravelNoteLike 的关联
  TravelNote.hasMany(TravelNoteLike, {
    foreignKey: 'note_id',
    as: 'likes'
  });
  TravelNoteLike.belongsTo(TravelNote, {
    foreignKey: 'note_id',
    as: 'note'
  });

  // User 和 TravelNoteFavorite 的关联
  User.hasMany(TravelNoteFavorite, {
    foreignKey: 'user_id',
    as: 'favorites'
  });
  TravelNoteFavorite.belongsTo(User, {
    foreignKey: 'user_id',
    as: 'user'
  });

  // TravelNote 和 TravelNoteFavorite 的关联
  TravelNote.hasMany(TravelNoteFavorite, {
    foreignKey: 'note_id',
    as: 'favorites'
  });
  TravelNoteFavorite.belongsTo(TravelNote, {
    foreignKey: 'note_id',
    as: 'note'
  });

  console.log('✅ Sequelize 模型关联配置完成');
};

// 测试连接
sequelize
  .authenticate()
  .then(() => {
    console.log('✅ MySQL 数据库连接成功');

    // 配置模型关联关系
    try {
      setupAssociations();
    } catch (error) {
      console.error('⚠️  模型关联配置失败:', error.message);
    }
  })
  .catch((err) => {
    console.error('❌ MySQL 数据库连接失败:', err);
  });

module.exports = sequelize;

